package com.aiyi.education.shiro;


import com.aiyi.education.admin.service.IKsAdminService;
import com.aiyi.education.entity.KsUser;

import com.aiyi.education.entity.KsUserWithBLOBs;
import com.aiyi.education.entity.admin.KsAdmin;
import com.aiyi.education.user.service.IKsUserService;
import com.education.base.Constant;
import com.education.base.PublicResultConstant;
import com.education.util.JWTUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * @author
 * @since 2018-05-03
 */
public class MyRealm extends AuthorizingRealm {

    IKsUserService ksUserService;
    IKsAdminService ksAdminService;

    /*private IHomeOwnerService homeOwnerService;
    private IPlatFormUserService platFormUserService;
    private IDecorationCompanyAccountService decorationCompanyAccountService;
    private ISupplierAccountService supplierAccountService;
    private IMenuService menuService;
    private IRoleService roleService;
    private IRoleToMenuService roleToMenuService;

    private IPersonnelFileService personnelFileService;
    private IUserToRoleService userToRoleService;
    private IDecorationCompanyRoleToAuthorityService decorationCompanyRoleToAuthorityService;
    private IDecorationCompanyRoleService decorationCompanyRoleService;
      */

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        if (ksUserService == null) {
            this.ksUserService = SpringContextBeanService.getBean(IKsUserService.class);
        }
        if (ksAdminService == null) {
            this.ksAdminService = SpringContextBeanService.getBean(IKsAdminService.class);
        }

        String userNo = JWTUtil.getUserNo(principals.toString());
        String loginType = JWTUtil.getLoginType(principals.toString());
        String getuserno = "";
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        /*if (Constant.UserLoginType.PLATFORM_ACCOUNT.equalsIgnoreCase(loginType)) {
            PlatFormUser userBean = platFormUserService.getUserByUserNo(userNo);
            getuserno = userBean.getUserNo();
            String userRole = null;
            int isadmin = 0;

            if (userBean != null) {
                getuserno = userBean.getUserNo();
                isadmin = userBean.getIsAdmin();

                if (userBean.getRole() != null) {
                    userRole = userBean.getRole();
                } else {

                }
            }


            if (isadmin > 0) {
                Set<String> roleNameSet = new HashSet<>();
                roleNameSet.add(Constant.UserLoginType.PLATFORM_ACCOUNT);
                //   roleNameSet.add(Constant.RoleType.USER);
                simpleAuthorizationInfo.addRoles(roleNameSet);
                ArrayList<String> pers = new ArrayList<>();
                pers.add("*"); //管理员开放所有权限

                Set<String> permission = new HashSet<>(pers);
                simpleAuthorizationInfo.addStringPermissions(permission);
            }

            if (userRole != null) {
                Role decorationCompanyRole = roleService.selectOne(new EntityWrapper<Role>().eq("role_code", userRole));
                if (decorationCompanyRole != null) {


                    Set<String> roleNameSet = new HashSet<>();
                    roleNameSet.add(decorationCompanyRole.getRoleName());
                    simpleAuthorizationInfo.addRoles(roleNameSet);

                    ArrayList<String> pers = new ArrayList<>();
                    List<Menu> menuList = roleToMenuService.getAuthList(userRole);   //roleAuthService.selectList(new EntityWrapper<DecorationCompanyRoleToAuthority>().eq("role_code", userRole));
                    for (Menu per : menuList) {
                        if (!ComUtil.isEmpty(per.getCode())) {
                            pers.add(String.valueOf(per.getCode()));
                        }
                    }
                    Set<String> permission = new HashSet<>(pers);
                    simpleAuthorizationInfo.addStringPermissions(permission);
                }
            }


        }*/

        KsUser userBean = ksUserService.getUserByUserNo(userNo);
        getuserno = userBean.getUserId().toString();
        Set<String> roleNameSet = new HashSet<>();
        roleNameSet.add("");
        //   roleNameSet.add(Constant.RoleType.USER);
        simpleAuthorizationInfo.addRoles(roleNameSet);
        ArrayList<String> pers = new ArrayList<>();

        pers.add("" + ":*"); //开放所有权限

        Set<String> permission = new HashSet<>(pers);
        simpleAuthorizationInfo.addStringPermissions(permission);


        // User user = userService.selectById(userNo);
        //  UserToRole userToRole = userToRoleService.selectByUserNo(user.getUserNo());
        // UserToRole userToRole = userToRoleService.selectByUserNo(getuserno);
        //   SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // Role role = roleService.selectOne(new EntityWrapper<Role>().eq("role_code", userToRole.getRoleCode()));
        //添加控制角色级别的权限
        //  Set<String> roleNameSet = new HashSet<>();
        //   roleNameSet.add(role.getRoleName());
        //  simpleAuthorizationInfo.addRoles(roleNameSet);

        //控制菜单级别按钮  类中用@RequiresPermissions("user:list") 对应数据库中code字段来控制controller
        /*
        ArrayList<String> pers = new ArrayList<>();
        List<Menu> menuList = menuService.findMenuByRoleCode(userToRole.getRoleCode());
        for (Menu per : menuList) {
             if (!ComUtil.isEmpty(per.getCode())) {
                  pers.add(String.valueOf(per.getCode()));
              }
        }
        Set<String> permission = new HashSet<>(pers);
        simpleAuthorizationInfo.addStringPermissions(permission);

        */
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws UnauthorizedException {
  /*
        if (userService == null) {
            this.userService = SpringContextBeanService.getBean(IUserService.class);
        }
  */

        if (this.ksUserService == null) {
            this.ksUserService = SpringContextBeanService.getBean(IKsUserService.class);
        }
        if (this.ksAdminService == null) {
            this.ksAdminService = SpringContextBeanService.getBean(IKsAdminService.class);
        }

        String token = (String) auth.getCredentials();
        if (Constant.isPass.get()) {
            return new SimpleAuthenticationInfo(token, token, this.getName());
        }
        // 解密获得username，用于和数据库进行对比
        String userNo = JWTUtil.getUserNo(token);

        if (userNo == null) {
            throw new UnauthorizedException("token invalid");
        }
        // User userBean = userService.selectById(userNo);
        String loginType = JWTUtil.getLoginType(token);

        String getuserno = "";
        if (Constant.UserLoginType.ADMIN.equals(loginType)){
            KsAdmin userBean = ksAdminService.getById(userNo);
            if (userBean == null) {
                throw new UnauthorizedException(PublicResultConstant.INVALID_USER);
            }
            if (!JWTUtil.verify(token, userNo, userBean.getPassword())) {
                throw new UnauthorizedException(PublicResultConstant.INVALID_USERNAME_PASSWORD);
            }
        }else{
            KsUserWithBLOBs userBean = ksUserService.getById(userNo);
            if (userBean == null) {
                throw new UnauthorizedException(PublicResultConstant.INVALID_USER);
            }
            if (!JWTUtil.verify(token, userNo, userBean.getPassword())) {
                throw new UnauthorizedException(PublicResultConstant.INVALID_USERNAME_PASSWORD);
            }
        }



        return new SimpleAuthenticationInfo(token, token, this.getName());
    }
}
